package io;

import org.junit.jupiter.api.Test;

import java.io.FileReader;
import java.io.IOException;

/**
 *  文件输入流-FileReader
 */
public class FileReader_ {

    public static void main(String[] args) {

        /*
            使用 FileReader 从 story.txt 读取内容，并显示
         */
    }

    //演示单个字符读取
    @Test
    public void fileReader01() {

        String filePath = "D:\\IdeaCode\\javaStudy\\story.txt";

        FileReader fr = null;
        int readLen = 0;

        try {
            fr = new FileReader(filePath);
            //单个字符循环读取
            while ((readLen = fr.read()) != -1) {
                System.out.print((char) readLen);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 使用多个字符读取
    @Test
    public void fileReader02() {
        String filePath = "D:\\IdeaCode\\javaStudy\\story.txt";

        FileReader fr = null;
        char[] buf = new char[8];   // 字符数组读取
        int readLen = 0;

        try {
            fr = new FileReader(filePath);
            //单个字符循环读取
            while ((readLen = fr.read(buf)) != -1) {
                System.out.print(new String(buf, 0, readLen));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
